/**
 * @class Digu
 * @fileOverview 嘀咕微博控制器
 * @extends yijs.air.Controller
 */ 
var Digu = function(user){
	//配置信息
	this.config			  = yijs.config.digu || {};
	this.cls = this.config.cls;		
	this.field = this.config.field || {};
	//模型
	this.ModelOption	  = new Option();
	this.ModelTemp  	  = new Temp();
	this.ModelMsg    	  = new Msg();
	//服务器端返回的数据类型
	this.type 			  = yijs.config.dataType[1];
	//语言
	this.lang 			  = yijs.lang.digu;
	//视图路径
	this.viewPath         = helpYi.getViewPath(yijs.config.viewName.digu);
	this.itemsViewPath    = helpYi.getViewPath(yijs.config.viewName.diguItems);
	//用户信息
	this.user             = user;
	this.authorization	  = _getAuthorization(this.user.name,this.user.password);
	
	this.ajaxApplyTo      = yijs.config.ajax.applyTo;
	this.id               = this.config.id;
	this.contentContainer = "MAIN_CONTENT";
	this.$content         = null;
	
	//获取http验证
	function _getAuthorization(name,password){
		var name 		  = name;
		var password      = password;
		var Authorization = "Basic " + Base64.encode(name+":"+password);
		return Authorization;		
	}
}

Digu.prototype.API = "http://api.minicloud.com.cn/";
Digu.prototype.APIURI = ['search','statuses','users','friendships','direct_messages','account','tag','register','help','favorites','blocks'];
Digu.prototype.ACTION = {
		/**搜索*/
		search : "search",
		/**显示大家在做啥*/
		publicMsg : "public_timeline",
		/**显示用户在做啥*/
		userMsg : "user_timeline",
		/**显示用户和好友在做啥*/
		friendsMsg : "friends_timeline",
		/**获取一条指定的消息*/
		getMsg : "show",
		/**发布一条新消息*/
		updateMsg : "update",
		/**删除一条消息*/
		delMsg : "destroy",
		/**获取一条指定的消息*/
		getMentions : "mentions",
		/**用户验证*/
		verify : "verify",
		user : "show"		
}
/**
 * 用户认证
 * @param {Object} Authorization 认证信息
 * @param {Object} success 认证成功后的回调函数
 */
Digu.prototype.verify = function(Authorization,success){
		var _that = this;
		var url = this.getUrl(5,"verify");
		helpYi.proxy({url : url,
		              Authorization : Authorization,
					  success : function(data){
					  	if(success) success.call(this,data);
					  }
		});	
}
/**
 * 读取并解析模板
 */
Digu.prototype.view = function(){
	var _that = this;
	var langsXml = getLangXml(this.lang);
	yijs.air.view(langsXml,
				  {url:this.viewPath},"body",null,false,
				  function(renderTo,result){
				  		helpYi.viewChangeEffect.fade(renderTo,result);
						_that.viewHandler();
				  });
	
}
/**
 * 解析完模板后触发的事件
 * @param {Object} xml
 * @param {Object} xsl
 */
Digu.prototype.viewHandler = function(){
	var _that = this;
	this.$content = $("#"+this.id).children("#"+this.contentContainer); 	
	_navHover();
	yijs.hover("#SET > li",_that.cls.mySetLiHover);
	$("#FACE").click(function(event){
		$("#MAIN_TOP_NAV").show("slow",'easeInOutBounce');
		return false;
	})
	$("#MAIN_TOP_NAV").click(function(){return false;})
	$("body").click(function(){$("#MAIN_TOP_NAV").hide("slow",'easeOutBounce');})
	this.setNavHeaderSlide();
	this.setUser();	
	this.getMyMsg();
	
	$("#NAV_MSG").click(function(){
		_that.removeItems(function(){
			_that.getMyMsg();
		});
		
	})
	
	$("#USER").click(function(){
		_that.setUser();	
	})
	
	//鼠标移过移开菜单项
	function _navHover(){
		$("#LEFT_NAV > li").hover(function(){
			if(!$(this).hasClass(_that.cls.navItemCurrent)){
				$(this).addClass(_that.cls.navItemOver);
				
			}
			var _w = $(this).outerWidth();
			var _index = $("#LEFT_NAV > li").index($(this));
			var _gap =  _w * _index;
			$("#MASK").stop().animate({"left":_gap},'normal','easeOutBounce');
		},function(){
			if(!$(this).hasClass(_that.cls.navItemCurrent)){
				$(this).removeClass(_that.cls.navItemOver);
			}		
		})		
	}
	
}
/**
 * 获取用户信息,并予以显示
 */
Digu.prototype.setUser = function(){
	var _that = this;
	//请求时需要的参数
	var _param = this.user.name;
	//API路径
	var _url = this.getUrl(2,"user",_param);
	//预加载信息
	var _preLoadMsg = this.lang.user;
	//开始获取
	helpYi.proxy({url : _url,
	              Authorization : this.authorization,
				  preLoadMsg : _preLoadMsg,
				  success : function(data){
				  	_setUserHandler(data);
				  }
	});		
	
	/**
	 * @private
	 * 处理ajax返回的数据
	 * @param {Object} data xml数据
	 */	
	function _setUserHandler(data){
				var user 		= helpYi.xml2json($(data).find(_that.field.user));
				var _faceSizes  = _that.config.faceSizes;
				var _male   = _that.lang.male;
				var _female = _that.lang.female;				
				$("#USERNAME").text(user["screen_name"]);
				//写入用户信息列表
				$("#SHOW_NAMW").text(user["screen_name"]);
				$("#REGISTER_NAME").text(user["name"]);
				$("#LOCATION").text(user["location"]);
				$("#GENDER").text(Number(user["gender"]) == 1 && _male || _female);
				$("#FOLLOWERS_COUNT").text(user["followers_count"]);
				$("#FRIENDS_COUNT").text(user["friends_count"]);
				//修改头像大小（默认头像为24x24，过小了）
				var _face = user["profile_image_url"];
				var _reg = /24x24/;
				_face = _face.replace(_reg,_faceSizes[2]);
				$("#FACE").children("img").attr("src",_face);
				$("#MY_DETAILS_FACE > img").attr("src",user["profile_image_url"].replace(_reg,_faceSizes[1]));
				//写入缓存
				$("#USERNAME").data(user);	
	}		
}
/**
 * 获取我的信息
 */
Digu.prototype.getMyMsg = function(){
	var _that = this;
	var _name = this.user.name;
	var _action = "userMsg";
	var _testApi = "App:/json/user.xml"
	//API路径
	var _url = this.getUrl(1,_action);
	//预加载信息
	var _preLoadMsg = this.lang.myMsg;
	//开始获取
	helpYi.proxy({url : _url,
			      data : {"userIdOrName":_name},
	              Authorization : this.authorization,
				  preLoadMsg : _preLoadMsg,
				  success : function(data){
				  	_that.showMsgHandler(_action,data);
				  }
	});			
	
}
/**
 * 显示信息
 * @param {String} action 		动作
 * @param {Object} data xml		数据源
 */
Digu.prototype.showMsgHandler = function(action,xml){
	var _that = this;
	this.insertDbMsg(action,xml,function(){
			_that.getMsg(action,1);			
	});
					
}
/**
 * 从数据库读取消息
 * @param {String} action	动作
 * @param {Number} page	    指定页数
 */
Digu.prototype.getMsg = function(action,page){
	var _that = this;
	var data = this.ModelMsg.getAssignMsgs(this.user.controller,action);
	if(data.length > 0){
		data = helpYi.jsonReverse(data); 
		var xml = helpYi.json2xml(data,"statuses","status",function(key,value){
			if(key == "created_at"){
				var date = new Date(Number(value));
				var timer = helpYi.formatTime(date.toGMTString());
				return timer;
			}
			return value;
		});
		yijs.air.view(xml,{url:this.itemsViewPath},"#MAIN_CONTENT",function(xml,xsl){
			_viewHandler();	
		},true);		
	}
	function _viewHandler(){
	    var $liOdd = _that.$content.find("li:odd");
		$liOdd.addClass(_that.cls.msgItemOdd);		
		var $li = _that.$content.find("li"); 
		var len = $li.size();
		var _delayTimer = 0;
		$li.each(function(){
			$(this).delay(_delayTimer).fadeIn("fast");
			_delayTimer += 200;
		})
			
	}		
}
/**
 * 将消息插入到xml
 * @param {String} action 		动作
 * @param {Object} data xml		数据源
 * @param {Function} fnCallBack 插入完成后回调函数
 * @return {Boolean}
 */
Digu.prototype.insertDbMsg = function(action,data,fnCallBack){
	var _controller = this.user.controller;
	var _action = action;
	//最后获取时间戳的key名
	var _lastGetTimerField = _controller + "_" + _action + "_" + "last_timer";
	var $status = $(data).find("status");
	var _size = $status.size();
	if(_size > 0){
		for(var i = _size-1 ;i >=0 ; i--){
				var _user = $status.eq(i).children("user");
				//将时间转化为时间戳
		        var date = new Date($status.eq(i).children("created_at").text());
				var _created_at = date.getTime();	
				//获取最后获取时间戳
				var _lastGetTimer = this.ModelTemp.get(_lastGetTimerField);
				//大于最后获取时间戳写入到数据库
				if(_created_at > _lastGetTimer){
					var _data = {controller             : _controller,action :_action,
					             msg_id                 : $status.eq(i).children("id").text(),
								 created_at             : _created_at,
								 text                   : $status.eq(i).children("text").text(),
								 source                 : $status.eq(i).children("source").text(),
								 user_id                : _user.children("id").text(),
								 user_name              : _user.children("name").text(),
								 user_screen_name       : _user.children("screen_name").text(),
								 user_location          : _user.children("location").text(),
								 user_description       : _user.children("description").text(),
								 user_profile_image_url : _user.children("profile_image_url").text(),
								 user_url               : _user.children("url").text(),
								 user_protected         : _user.children("protected").text()
					}
					this.ModelMsg.insert(_data);							
				}
				//更新最后获取时间戳
				i == 0 && this.ModelTemp.update(_lastGetTimerField,_created_at);		 			
		}
		if(fnCallBack) fnCallBack.call(this);
	}
	return true;			 
}
/**
 * 从数据库提取我的消息并予以显示
 */
Digu.prototype.setMyMsg = function(){
	var _controller = this.user.controller;
	var _action = Zuosa.ACTION.userMsg;	
	var result = this.ModelMsg.getAssignMsgs(_controller,_action);
}

/**
 * 删除内容
 */
Digu.prototype.removeItems = function(fnCallBack){
	var $li = this.$content.find("li"); 
	var len = $li.size();
	if(len > 0){
			_animate(len-1);
			/**
			 * li隐藏动画
			 * @param {Object} eq
			 */	
			function _animate(eq){
				$li.eq(eq).fadeOut("fast",function(){
					eq > 0 && eq -- && $(this).remove() && _animate(eq);						
					if(fnCallBack && eq == 0)  fnCallBack.call(this);
				})
			}
	}else{
		if(fnCallBack )  fnCallBack.call(this);
	}
}
Digu.prototype.setNavHeaderSlide = function(){
	var $slide = $("#NAV_HEADER_SLIDE");
	var ulWidth = $slide.parent().width();
	var $ul = $slide.children("ul");
	$ul.width(ulWidth);
	$slide.width(ulWidth * $ul.size());
	
	var $li = $("#LEFT_NAV > li");
	$li.mouseover(function(){
		var index = $li.index($(this));
		var marginLeft = index == 0 && 0 || "-" + index * ulWidth;
		$slide.stop().animate({"marginLeft": marginLeft},"fast");
	});
}
/**
 * 获取
 * @param {Object} apiUri
 * @param {Object} action
 * @param {Object} param
 */
Digu.prototype.getUrl = function(apiUri,action,param){
	var _url = this.API+this.APIURI[apiUri]+"/"+this.ACTION[action];
	if(param) _url += "/"+param;
	_url += "."+this.type;
	return _url;
}

